<?php
namespace app\index\controller;
use think\Db;
use my\Security;
use my\Tools;
use think\Model;
use think\Controller;
use think\mongo\Connection;
use think\Request;
use think\Session;
class Index extends Controller
{
    //
    public function index()
    {
        $info = [
            'type'              => 'driver',
            'registration_id'   => '141fe1da9ec2030cd07',
            'sendType'          => 'systemCancelOrder',
            'order_sn'          => '1111',
        ];
        echo "<pre>";
        print_r($info);
        exit;
        /*$res = sendjg($info,'测试','测试123456',2);
        print_r($res);die;*/
        /*$umid = 14419;//;
        $userList       = Db::name('user')->where(['false_status'=>1])->field('uid,user_phone')->select();
        $time           = time() - rand(1,9999);
        $reinfo = $bugGift = $result = $infomation = [];
        foreach($userList as $key=>$value){
            if($key > 280 && $key < 390){
                $result         = Db::table('xm_user_recommend_record')->where(['uid'=>$umid])->find();
                $recommend_id   = $result['recommend_id'];
                $recomInfo = Db::table('xm_user_recommend_record')->where(['uid'=>$value['uid']])->find();
                if(empty($recomInfo)){
                    //推荐关系入库
                    $reinfo = [
                        'uid'                   => $value['uid'],
                        'recommend_id'          => $umid,
                        'indirect_recommend_id' => $recommend_id,
                        'add_time'              => $time,
                        'update_time'           => $time + rand(60,360),
                        'equities_to_buy'       => 1,
                        'equities_num'          => 1,
                        'recommend_num'         => 0,
                        'recommend_equities_num'=> 0,
                        'indirect_recommend_num'=> 0,
                        'indirect_recommend_equities_num'=> 0,
                    ];
                    Db::table('xm_user_recommend_record')->insertGetId($reinfo);
                    //生成购买礼包记录
                    $status = rand(0,1);
                    $bugGift = [
                        'uid'                   => $value['uid'],
                        'add_time'              => $reinfo['update_time'],
                        'recommend_id'          => $umid,
                        'indirect_recommend_id' => $recommend_id,
                        'status'                => rand(0,1),
                        'update_time'           => $status == 1?$reinfo['update_time']+rand(360,960):'',
                        'pay_money'             => 39800,
                        'is_common'             => 1,
                        'pay_type'              => 4
                    ];
                    Db::table('xm_gift_purchase_record')->insertGetId($bugGift);
                    //生成钱包
                    $hbShare = [
                        'uid'       => $value['uid'],
                        'add_time'  => $time
                    ];
                    Db::table('hb_share_profit_money')->insertGetId($hbShare);
                    //给直接推荐人增加数据
                    $infomation = [
                        'recommend_num'             => $result['recommend_num'] + 1,
                        'recommend_equities_num'    => $result['recommend_equities_num'] + 1,
                    ];
                    Db::table('xm_user_recommend_record')->where(['uid'=>$umid])->update($infomation);
                    //给直接推荐人增加分润
                    if($status == 1){
                        $recommendInfo = Db::table('hb_share_profit_money')->where(['uid'=>$umid])->find();
                        Db::table('hb_share_profit_money')->where(['uid'=>$umid])->update(['money'=>$recommendInfo['money']+10000,'sum_money'=>$recommendInfo['sum_money']+10000]);
                    }
                    //给直接推荐人增加分润记录
                    $recommendShareInfo = [
                        'uid'           => $umid,
                        'money'         => 10000,
                        'type'          => $status == 1?1:2,
                        'add_time'      => $bugGift['update_time'],
                        'phone'         => Security::decrypt($value['user_phone']),
                        'recommend_type'=> 1
                    ];
                    Db::table('hb_share_profit_wallet_record')->insertGetId($recommendShareInfo);
                    //查询间接推荐人信息
                    $indirectInfo   = Db::table('xm_user_recommend_record')->where(['uid'=>$recommend_id])->find();
                    //给间接推荐人增加记录
                    $infomationArr = [
                        'indirect_recommend_num'             => $indirectInfo['indirect_recommend_num'] + 1,
                        'indirect_recommend_equities_num'    => $indirectInfo['indirect_recommend_equities_num'] + 1,
                    ];
                    Db::table('xm_user_recommend_record')->where(['uid'=>$recommend_id])->update($infomationArr);
                    //给间接推荐人增加分润
                    if($status == 1){
                        $indirectInfoArr = Db::table('hb_share_profit_money')->where(['uid'=>$recommend_id])->find();
                        Db::table('hb_share_profit_money')->where(['uid'=>$recommend_id])->update(['money'=>$indirectInfoArr['money']+3000,'sum_money'=>$indirectInfoArr['sum_money']+3000]);
                    }
                    //给间接推荐人增加分润记录
                    $indirectInShareInfo = [
                        'uid'           => $recommend_id,
                        'money'         => 3000,
                        'type'          => $status == 1?1:2,
                        'add_time'      => $bugGift['update_time']?$bugGift['update_time']:$time,
                        'phone'         => Security::decrypt($value['user_phone']),
                        'recommend_type'=> 2
                    ];
                    Db::table('hb_share_profit_wallet_record')->insertGetId($indirectInShareInfo);
                }
            }
        }
        print_r($result);die;*/
        //print_r($data);die;
        /*$userList = Db::name('user')->where(['is_del'=>1,'referee_id'=>16888])->select();
        $uidStr = '';
        echo count($userList)."<hr/>";
        foreach ($userList as $key=>$value){
            $uidStr .= $value['uid'].',';
        }
        $aa = Db::name('user')->where(['referee_id'=>['in',rtrim($uidStr,',')]])->select();
        echo count($aa)."<hr/>";
        echo Db::name('user')->where(['invite_id'=>16888])->count();*/
        //$mongoCollection = new Connection();
        //$mongoCollection->name("driver_location")->insertGetId(['driverId'=>140]);
        //$where['driverId'] = 120;
        //$test1=$mongoCollection->table("driver_location")->where($where)->find();
        //$mongoCollection->table('driver_location')->where($where)->update(['driverId'=>130]);
        //$mongoCollection->table('driver_location')->where($where)->delete();

        //$map['location'] = ['geo within',['$center'=>[[floatval(117.300944),floatval(31.832975)],5000]]];
        //$map = ['location'=>['nears',[floatval(117.300944),floatval(31.832975),5000]]];
        //print_r($map);die;
        //$test1 = $mongoCollection->table('live_user_location')->where(['location'=>['geo within',[floatval(117.300944),floatval(31.832975),5000]]])->select();
        //$test1 = $mongoCollection->table('live_user_location')->where($map)->select();
        //print_r($test1);die;
//        $db2 = Db::connect('db2');
        //print_r($db2);die;
        //$res_data = $db2->table('xm_user')->where('id',1)->find();
//        $res_data = Db::table('xm_user')->where('uid',78093)->update(['is_delete'=>1]);
//        exit();
        /*$uid = 389598;
        $userList = Db::name('user')->where(['fr_driver_referee_id'=>$uid])->field('uid')->select();
        $userArr = [];
        foreach ($userList as $key=>$value){
            $userArr[] = $value['uid'];
        }
        $driverList = Db::table('fr_driver_base')->where(['driver_uid'=>['in',implode(',',$userArr)],'add_time'=>['between',['1565539200','1569772800']],'auth_status'=>1])->field('driver_uid,register_city,check_pass_time')->select();
        foreach ($driverList as $key=>$value){
            $driverList[$key]['check_pass_time'] = date("Y-m-d H:i:s",$value['check_pass_time']);
        }
        echo count($driverList)."<hr/>";
        //奖励记录
        $activityList = Db::name('activity_record')->where(['xm_admin_activity_id'=>8,'uid'=>$uid,'add_time'=>['between',['1565539200','1569772800']]])->select();
        $result = [];
        foreach ($activityList as $key=>$value){
            $add_time = date("Y-m-d H:i",$value['add_time']);
            $result[$add_time][] = $value['id'];
        }
        foreach ($result as $key=>$value){
            if(count($value) > 1){
                foreach ($value as $kml=>$val){
                    if($kml > 0){
                        //删除奖励记录
                        //Db::name('activity_record')->where('id',$val)->delete();
                    }
                }
            }
        }
        echo count($result)."<hr/>";
        print_r($result);
        //流水记录
        $user_recharge = Db::name('user_recharge')->where(['uid'=>$uid,'money_statement'=>12,'time'=>['between',['1565539200','1569772800']]])->select();
        foreach ($user_recharge as $key=>$value){
            $time = date("Y-m-d H:i",$value['time']);
            $resultAry[$time][] = $value['money_id'];
        }
        foreach ($resultAry as $key=>$value){
            if(count($value) > 1){
                foreach ($value as $kml=>$val){
                    if($kml > 0){
                        //删除流水记录
                        //Db::name('user_recharge')->where('money_id',$val)->delete();
                    }
                }
            }
        }
        echo count($resultAry)."<hr/>";
        print_r($resultAry);
        //消息发送记录
        $passenger_message = Db::name('passenger_message')->where(['uid'=>$uid,'title'=>'邀请车主认证','send_time'=>['between',['1565539200','1569772800']]])->select();
        foreach ($passenger_message as $key=>$value){
            $send_time = date("Y-m-d H:i",$value['send_time']);
            $resultAryArr[$send_time][] = $value['mes_id'];
        }
        foreach ($resultAryArr as $key=>$value){
            if(count($value) > 1){
                foreach ($value as $kml=>$val){
                    if($kml > 0){
                        //删除消息记录
                        //Db::name('passenger_message')->where('mes_id',$val)->delete();
                    }
                }
            }
        }
        echo count($resultAryArr)."<hr/>";
        print_r($resultAryArr);
        die;*/
        /*$str = [13691,13690,13689,13688,13687,13686,13685,13684,13683,13682,13681,13680,13679,13678,13677,13676,13675,13674,13673,13672,13671,13670,13669,13668,13667,13666,13665,13664,13663,13662,13661,13660,13659,13658,13657,13656,13655,13654,13653,13652,13651,13650,13649,13648,13647,13646,13645,13644,13643,13642,13641,13640,13639,13638,13637,13636,13635,13634,13633,13632,13631,13630,13629,13628,13627,13626,13625,13624,13623,13622,13621,13620,13619,13618,13617,13616];
        //$start_time     = strtotime('2019-09-27');
        //$end_time       = strtotime('2019-09-28 23:59:59');
        $activityList   = Db::name('activity_record')->where(['id'=>['in',$str]])->field('id,xm_admin_activity_id,uid,user_type,amount,account_time')->select();
        //echo Db::name('activity_record')->getLastSql();die;
        //print_r($activityList);die;
        $result = $list = $driverMoney = $driverWallet = [];
        foreach ($activityList as $key=>$value){
            //$result[$value['xm_admin_activity_id']][] = $value;
            if($value['user_type'] == 2){       //司机
                //查询司机 - 账户
                $driverMoney = Db::name('driver_money')->where(['driver_id'=>$value['uid']])->find();
                //查询司机流水
                $driverWallet = Db::name('driver_wallet_record')->where(['driver_id'=>$value['uid'],'record_type'=>4,'money'=>$value['amount'],'time'=>$value['account_time']])->find();
                if(!empty($driverMoney) && $driverWallet){
                    //开始处理司机账户 - 司机流水
                    if($driverMoney['award_balance'] > $value['amount']){
                        $driverMoneyArr = [
                            'money'         => $driverMoney['money'] - $value['amount'],
                            'award'         => $driverMoney['award'] - $value['amount'],
                            'award_balance' => $driverMoney['award_balance'] - $value['amount'],
                        ];
                        //司机流水更新
                        Db::name('driver_money')->where(['driver_id'=>$value['uid']])->update($driverMoneyArr);
                        //删除司机流水
                        Db::name('driver_wallet_record')->where(['record_id'=>$driverWallet['record_id']])->delete();
                        Db::name('activity_record')->where(['id'=>$value['id']])->delete();
                    }else{
                        $result[] = $value;
                    }
                }else{
                    $result[] = $value;
                }
            }else{
                $result[] = $value;
            }
        }
        file_put_contents(RUNTIME_PATH . 'log/' . date('123456-Ymd') . '.txt', print_r($result, true), FILE_APPEND);
        print_r($result);
        die;*/
        //print_r($result);die;*/
        return $this->fetch();
    }
    //生成顺风车订单
    public function create_order(){
        $key        = input('get.key');
        if($key != '4b77GPiD8nYWh5httjYqu'){
            echo '请输入正确的秘钥';die;
        }
        $cityList = Db::name('region')->where(['parent_id'=>13,'region_level'=>2])->field('region_id')->select();
        $cityStr = '';
        foreach ($cityList as $key=>$value){
            $cityStr .= $value['region_id'].',';
        }
        $cityArr = explode(',',rtrim($cityStr,','));
        //根据手机号码查询 司机和用户
        $driverPhoneArr = ['18895339551','18755162887','18856056549','18164488681','17681036684','17333108849','13275516191','18715070612','18810838709','13721042845'];
        $driverKey  = array_rand($driverPhoneArr,1);
        $userPhoneArr = ['18164488681','17681036684','13966793174','13645651242','17756571801','15156572928','18715070612','13275516191','17333108849','18856056549','18255194501','18755184361','13721042845','19956053485','18810838709','18075070729','18956188612','18605542769','18141901466'];
        $userKey    = array_rand($userPhoneArr,1);
        if($driverPhoneArr[$driverKey] == $userPhoneArr[$userKey]){
            if($userKey >= 16){
                $userKey - rand(1,5);
            }else{
                $userKey + rand(1,2);
            }
        }
        //查询司机UID
        $driver_uid = Db::name('user')->where(['user_phone'=>Security::encrypt($driverPhoneArr[$driverKey])])->value('uid');
        //查询司机姓名
        $driver_name = Db::table('fr_driver_base')->where(['driver_uid'=>$driver_uid])->value('driver_name');
        //查询乘客UID
        $user_id    = Db::name('user')->where(['user_phone'=>Security::encrypt($userPhoneArr[$userKey])])->value('uid');
        //查询安徽省所有顺风车订单
        $orderList = Db::table('fr_order_common')->where(['region_id'=>['in',rtrim($cityStr,',')],'is_del'=>2,'order_status'=>['>=',40],'need_price'=>['>',0]])->select();
        $random_keys = array_rand($orderList,1);
        $type = rand(1,2);
        unset($orderList[$random_keys]['common_id']);//删除主键ID
        $orderList[$random_keys]['uid'] = $user_id;
        $orderList[$random_keys]['driver_uid'] = $driver_uid;
        $orderList[$random_keys]['driver_name'] = $driver_name;
        $orderList[$random_keys]['driver_phone'] = Security::encrypt($driverPhoneArr[$driverKey]);
        $type = 2;
        if($type == 2){     //终点起点掉换
            $orderList[$random_keys]['order_name'] = $orderList[$random_keys]['arrive_name'].'附近';
            $start_name                                 = $orderList[$random_keys]['start_name'];  //起点
            $arrive_name                                = $orderList[$random_keys]['arrive_name']; //终点
            $start_local                                = $orderList[$random_keys]['start_local'];  //起点坐标
            $start_code                                 = $orderList[$random_keys]['start_code'];    //起点代码
            $arrive_local                               = $orderList[$random_keys]['arrive_local']; //终点坐标
            $arrive_code                                = $orderList[$random_keys]['arrive_code'];  //终点代码
            $orderList[$random_keys]['start_name']      = $arrive_name;
            $orderList[$random_keys]['arrive_name']     = $start_name;
            $orderList[$random_keys]['start_local']     = $arrive_local;
            $orderList[$random_keys]['start_code']      = $arrive_code;
            $orderList[$random_keys]['arrive_local']    = $start_local;
            $orderList[$random_keys]['arrive_code']     = $start_code;

        }
        list($s1, $s2) = explode(' ', microtime());
        $haomiao = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
        $time = substr($haomiao,-4);
        $orderList[$random_keys]['order_time']      = time() + rand(200,360);
        $orderList[$random_keys]['order_sn']        = 'FR'.date("YmdHis",$orderList[$random_keys]['order_time']).$time;
        $orderList[$random_keys]['on_car_time']     = $orderList[$random_keys]['order_time'] + rand(100,720);
        $orderList[$random_keys]['off_car_time']    = $orderList[$random_keys]['on_car_time'] + rand(2200,3600);
        $orderList[$random_keys]['passenger_phone'] = Security::encrypt($userPhoneArr[$userKey]);
        $orderList[$random_keys]['start_time']      = $orderList[$random_keys]['on_car_time'] + rand(10,100);
        $orderList[$random_keys]['false_status']    = 1;
        Db::table('fr_order_common')->insertGetId($orderList[$random_keys]);
    }

    //生成用户数据
    public function create_aa(){
        set_time_limit(0);
        $key        = input('get.key')?input('get.key'):input('post.key');
        $start      = input('post.start');
        $end        = input('post.end');
        $usercount  = input('post.usercount');
        if($key != '4b77GPiD8nYWh5httjYqu'){
            echo '请输入正确的秘钥';die;
        }
        if(!empty($end)){
            $miao = rand(1,10);
            sleep($miao);
            for($i=1;$i<=$end;$i++){
                $phone = 1;
                $phone .= rand(3,9);
                $phone .= rand(0,9);
                $phone .= rand(1000,9999);
                $phone .= rand(1000,9999);
                $userInfo = Db::name('user')->where(['user_phone'=>Security::encrypt($phone)])->find();
                if(empty($userInfo)){//18湖北省 14福建省 12浙江省 13安徽省 28陕西省 24四川省
                    $register_time = time() + rand(20,60) - rand(0,10);
                    $last_login_time = $register_time + rand(20,60);
                    $a = [13,11];
                    //$a = [18,14,12,28,13,24];
                    //$a = [18,14,12,28,13,24];
                    //$a = [18,14,12,28,13,24];
                    //查询省份
                    $regionList = Db::name('region')->where(['region_id'=>['in',$a],'region_level'=>1])->field('region_id')->select();
                    $provinceStr = '';
                    foreach ($regionList as $key=>$value){
                        $provinceStr .= $value['region_id'].',';
                    }
                    $provinceArr = explode(',',rtrim($provinceStr,','));
                    $random_keys = array_rand($provinceArr,1);
                    //查询城市
                    $cityList = Db::name('region')->where(['parent_id'=>$provinceArr[$random_keys],'region_level'=>2])->field('region_id,region_name')->select();
                    $cityStr = '';
                    foreach ($cityList as $key=>$value){
                        $cityStr .= $value['region_id'].',';
                    }
                    $cityArr = explode(',',rtrim($cityStr,','));
                    $city_keys = array_rand($cityArr,1);
                    //通过手机号码 查询推荐人id
                    $referPhone = ['18164488681','17681036684','13966793174','13645651242','17756571801','15156572928','18715070612','13275516191','17333108849','18856056549','18255194501','18755184361','13721042845','19956053485','18810838709','18075070729','18956188612','18605542769','18141901466'];
                    $phone_keys = array_rand($referPhone,1);
                    $referee_id = Db::name('user')->where(['user_phone'=>Security::encrypt($referPhone[$phone_keys])])->value('uid');
                    $userArr=[
                        'user_phone'    => Security::encrypt($phone),
                        'user_pass'     => md5('abc123456'),
                        'register_time' => $register_time,
                        'last_login_time'=> $last_login_time,
                        'register_province'=>$provinceArr[$random_keys],
                        'register_city' => $cityArr[$city_keys],
                        'false_status'  => 1,
                        'is_del'        => 1,
                        'referee_id'    => !empty($referee_id)?$referee_id:'0'
                    ];
                    Db::name('user')->insertGetId($userArr);
                }
            }
            $start  = $start+$end;
            $sumNum = $start;
            return json_encode(['code'=>1,'starty'=>$start,'sumNum'=>$sumNum,'numll'=>$start+$end,'count'=>$usercount+$end]);
        }
        $userCount = Db::name('user')->where(['false_status'=>1])->count();
        $this->assign('key',$key);
        $this->assign('userCount',$userCount);
        return $this->fetch('create_user');
    }



    //每天生成用户数据
    public function every_day_user(){
        $key = input('get.key');
        if($key != '4b77GPiD8nYWh5httjYqu'){
            echo '请输入正确的秘钥';die;
        }
        $hours = date("H");
        if($hours >= 7 && $hours < 12){
            $num = rand(3,10);
        }elseif ($hours >= 12 && $hours < 14){
            $num = rand(2,10);
        }elseif ($hours >= 14 && $hours < 22){
            $num = rand(5,15);
        }elseif ($hours >= 22 && $hours < 1){
            $num = rand(2,10);
        }elseif ($hours >= 1 && $hours <= 6){
            $num = rand(1,3);
        }else{
            $num = rand(1,5);
        }
        for($i=1;$i<=$num;$i++){
            $phone = 1;
            $phone .= rand(3,9);
            $phone .= rand(0,9);
            $phone .= rand(1000,9999);
            $phone .= rand(1000,9999);
            $userInfo = Db::name('user')->where(['user_phone'=>Security::encrypt($phone)])->find();
            if(empty($userInfo)){
                /*概率*///18湖北省 14福建省 12浙江省 13安徽省 28陕西省 24四川省
                $prize_arr = array(
                    '0' => array('id'=>11,'prize'=>'江苏省','v'=>rand(5,10)),
                    '1' => array('id'=>13,'prize'=>'安徽省','v'=>rand(25,50)),
                    //'0' => array('id'=>18,'prize'=>'湖北省','v'=>rand(1,7)),
                    //'1' => array('id'=>14,'prize'=>'福建省','v'=>rand(3,9)),
                    //'2' => array('id'=>12,'prize'=>'浙江省','v'=>rand(5,10)),
                    //'3' => array('id'=>28,'prize'=>'陕西省','v'=>rand(7,12)),
                    //'4' => array('id'=>13,'prize'=>'安徽省','v'=>rand(30,85)),
                    //'5' => array('id'=>24,'prize'=>'四川省','v'=>rand(5,15)),
                );
                foreach ($prize_arr as $key => $val) {
                    $arr[$val['id']] = $val['v'];
                }
                $province_id = $this->get_rand($arr); //根据概率获取奖项id
                /*$proArr = [18,14,12,28];
                $proKey = array_rand($proArr,1);
                $dataProvince[] = $proArr[$proKey];
                $dataProvince[] = 13;
                $proArrly = [18,14,12,28];
                unset($proArrly[$proKey]);
                $proKeyly = array_rand($proArrly,1);
                $praa = $proArrly;
                unset($praa[$proKeyly]);
                $praaKey = array_rand($praa,1);*/
                $register_time = time();
                $register_time = $register_time + rand(0,20);
                $last_login_time = $register_time + rand(20,60);
                //查询省份
                /*$regionList = Db::name('region')->where(['region_id'=>['in',$dataProvince],'region_level'=>1])->field('region_id')->select();
                $provinceStr = '';
                foreach ($regionList as $key=>$value){
                    $provinceStr .= $value['region_id'].',';
                }
                $provinceArr = explode(',',rtrim($provinceStr,','));
                $random_keys = array_rand($provinceArr,1);
                $ProvinceInfo = session('province');
                if(!empty($ProvinceInfo)){
                    if($ProvinceInfo == $provinceArr[$random_keys] || $ProvinceInfo == $proArrly[$proKeyly] || $ProvinceInfo == $praa[$praaKey]){
                        $provinceArr[$random_keys] = 13;
                    }
                    session('province', $provinceArr[$random_keys]);
                }else{
                    session('province', $provinceArr[$random_keys]);
                }*/
                //查询城市
                $cityList = Db::name('region')->where(['parent_id'=>$province_id,'region_level'=>2])->field('region_id')->select();
                $cityStr = '';
                foreach ($cityList as $key=>$value){
                    $cityStr .= $value['region_id'].',';
                }
                $cityArr = explode(',',rtrim($cityStr,','));
                $city_keys = array_rand($cityArr,1);
                //通过手机号码 查询推荐人id
                $referPhone = ['18164488681','17681036684','13966793174','13645651242','17756571801','15156572928','17333108849','18856056549','18255194501','18755184361','13721042845','19956053485','18810838709','18075070729','18956188612','18605542769','10','11','33','55','44'];
                $phone_keys = array_rand($referPhone,1);
                $referee_id = Db::name('user')->where(['user_phone'=>Security::encrypt($referPhone[$phone_keys])])->value('uid');
                $userArr=[
                    'user_phone'    => Security::encrypt($phone),
                    'user_pass'     => md5('abc123456'),
                    'register_time' => $register_time,
                    'last_login_time'=> $last_login_time,
                    'register_province'=>$province_id,
                    'register_city' => $cityArr[$city_keys],
                    'false_status'  => 1,
                    'is_del'        => 1,
                    'referee_id'    => !empty($referee_id)?$referee_id:'0'
                ];
                Db::name('user')->insertGetId($userArr);
            }
        }
    }
    //概率
    function get_rand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }
    public function update_franch(){
        $key = input('get.key');
        if($key != '4b77GPiD8nYWh5httjYqu'){
            echo '请输入正确的秘钥';die;
        }
        $dbFranchisee = [
            'type'      => 'mysql',
            'hostname'  => 'xm.mysql.polardb.rds.aliyuncs.com',
            'database'  => 'franchisee',
            'username'  => 'upfranchisee',
            'password'  => 'zf2l2Yg4NdmB212G',
            'hostport'  => '3306'
        ];
        //查询加盟商信息表
        $franchiseeList = Db::name('franchisee')->where(['is_del'=>1,'organization_type'=>['in',[1,2,3]]])->select();
        $list = Db::connect($dbFranchisee)->name('part_company')->select();
        $referList = $franchInfo = [];
        Db::connect($dbFranchisee)->query("TRUNCATE TABLE `part_company`");
        Db::connect($dbFranchisee)->query("TRUNCATE TABLE `area_agent`");
        Db::connect($dbFranchisee)->query("TRUNCATE TABLE `station`");
        Db::connect($dbFranchisee)->query("TRUNCATE TABLE `promoter`");
        foreach ($franchiseeList as $key=>$value){
            //小马加盟商数据入库 - 更新到加盟商后台中  1分公司 2区县代理 3驿站
            $franchInfo = [
                'id'            => $value['id'],
                'province_id'   => $value['province_id'],
                'city_id'       => $value['city_id'],
                'company_name'  => $value['franchisee_name'],
                'legal_person'  => $value['username'],
                'contact_number'=> $value['phone'],
                'remark'        => $value['content'],
            ];
            if($value['organization_type'] == 1){
                //分公司数据入库操作
                Db::connect($dbFranchisee)->name('part_company')->insertGetId($franchInfo);
            }elseif ($value['organization_type'] == 2){
                //分公司数据入库操作
                Db::connect($dbFranchisee)->name('area_agent')->insertGetId($franchInfo);
            }elseif($value['organization_type'] == 3){
                //驿站数据入库操作
                Db::connect($dbFranchisee)->name('station')->insertGetId($franchInfo);
            }
            self::selectRefer($value['id'],$value['organization_type']);
        }
        echo '执行成功';
    }

    //加盟商找推廣員
    public function selectRefer($fid = '',$type = ''){
        //加盟商線上數據庫連接
        $dbFranchisee = [
            'type'      => 'mysql',
            'hostname'  => 'xm.mysql.polardb.rds.aliyuncs.com',
            'database'  => 'franchisee',
            'username'  => 'upfranchisee',
            'password'  => 'zf2l2Yg4NdmB212G',
            'hostport'  => '3306'
        ];
        $referList = Db::name('refer')->where(['fid'=>$fid,'status'=>1,'is_del'=>1])->field('name,uid,time')->select();

        foreach ($referList as $key=>$value){
            $promoterArr = [
                'name'              => $value['name'],
                'phone'             => userInfo($value['uid']),
                'organization_type' => $type,
                'organization_id'   => $fid,
                'xm_uid'            => $value['uid'],
                'create_uid'        => 1
            ];
            Db::connect($dbFranchisee)->name('promoter')->insertGetId($promoterArr);
        }
        $refer_id = '';
        //推廣員字符串
        foreach ($referList as $key=>$value){
            $refer_id .= $value['uid'].',';
        }
        $refer_id = rtrim($refer_id,',');
        $userList = Db::name('user')->where(['is_del'=>1,'referee_id'=>['in',[$refer_id]]])->field('uid')->select();
        foreach ($userList as $ll=>$vaml){
             Db::name('user')->where(['is_del'=>1,'uid'=>$vaml['uid']])->update(['organization_type'=>$type,'organization_id'=>$fid]);
        }
    }

    //按钮
     public function main()
    {
        $type = input('get.type');
        //查询2019/4/28日之后开通会员的数据信息
        $memberInfo = Db::name('member')->where(['start_time'=>['>=','1556380800']])->select();
        $countNumber = '0';
        foreach ($memberInfo as $key=>$value){
            //查询这个用户有几张优惠券
            $countNumber = Db::name('coupon')->where(['uid'=>$value['uid'],'admin_coupon_id'=>['in',[156,157]]])->count();
            if($countNumber >= 2){
                unset($memberInfo[$key]);
            }
        }
        if($type == 1){
            print_r($memberInfo);die;
        }
        if($type == 2){
            //开始发放优惠券
            $time = time();
            if(!empty($memberInfo)){
                $cityId = '';
                foreach ($memberInfo as $key=>$value){
                    //先查询这人所属城市ID
                    $cityId = Db::name('user')->where(['uid'=>$value['uid']])->value('register_city');
                    $couponInfo = Db::table('xm_admin_coupon')->where(['start_time'=>['<=',$time],'end_time'=>['>=',$time],'order_type'=>4,'is_recommed'=>3,'model'=>2,'status'=>1,'coupon_id'=>['in',[156,157]]])->where("FIND_IN_SET('$cityId',region_id)")->order('coupon_id desc')->select();
                    if(!empty($couponInfo)){
                        $reult = [];
                        foreach($couponInfo as $kml=>$vall) {
                            $reult = [
                                'coupon_price'      => $vall['money'],
                                'uid'               => $value['uid'],
                                'start_time'        => $vall['start_time'],
                                'end_time'          => $vall['end_time'],
                                'valid_start_time'  => $vall['valid_start_time'],
                                'valid_end_time'    => $vall['valid_end_time'],
                                'is_use'            => 2,
                                'coupon_name'       => $vall['coupon_name'],
                                'region_id'         => $cityId,
                                'order_type'        => $vall['order_type'],
                                'admin_coupon_id'   => $vall['coupon_id'],
                                'model'             => $vall['model'],
                                'is_receive'        => 1,
                                'receive_time'      => time(),
                                'is_notice'         => 1
                            ];

                            if($vall['type_day'] == 2){
                                if(empty($vall['start_day'])){
                                    $timeL = strtotime(date("Y-m-d"));
                                }else{
                                    $timeL = strtotime(date("Y-m-d")) + 3600*24*$vall['start_day'];
                                }
                                $reult['valid_start_time']  = $timeL;
                                $end_time  = $time + 3600*24*$vall['duration_day'];
                                $reult['valid_end_time']    = strtotime(date("Y-m-d",$end_time)." 23:59:59");
                            }
                            //print_r($reult);die;
                            Db::name('coupon')->insertGetId($reult);
                        }
                    }
                }
            }
        }



        exit;
        /*$info = Db::name('coupon')->where(['admin_coupon_id'=>155])->select();
        foreach($info as $key=>$value){
            $memberInfo = Db::name('member')->where(['uid'=>$value['uid']])->find();
            if(empty($memberInfo)){
                unset($info[$key]);
            }
        }
        $time = time();
        foreach ($info as $key=>$value){
            //查询优惠信息
            $couponInfo = Db::table('xm_admin_coupon')->where(['start_time'=>['<=',$time],'end_time'=>['>=',$time],'order_type'=>4,'is_recommed'=>3,'model'=>2,'status'=>1,'coupon_id'=>['in',[156,157]]])->where("FIND_IN_SET('$value[region_id]',region_id)")->order('coupon_id desc')->select();
            if(!empty($couponInfo)){
                $reult = [];
                foreach($couponInfo as $kml=>$vall){
                    $reult = [
                        'coupon_price'      => $vall['money'],
                        'uid'               => $value['uid'],
                        'start_time'        => $vall['start_time'],
                        'end_time'          => $vall['end_time'],
                        'valid_start_time'  => $vall['valid_start_time'],
                        'valid_end_time'    => $vall['valid_end_time'],
                        'is_use'            => 2,
                        'coupon_name'       => $vall['coupon_name'],
                        'region_id'         => $value['region_id'],
                        'order_type'        => $vall['order_type'],
                        'admin_coupon_id'   => $vall['coupon_id'],
                        'model'             => $vall['model'],
                        'is_receive'        => 1,
                        'receive_time'      => time(),
                        'is_notice'         => 1
                    ];
                    if($vall['type_day'] == 2){
                        if(empty($vall['start_day'])){
                            $timeL = strtotime(date("Y-m-d"));
                        }else{
                            $timeL = strtotime(date("Y-m-d")) + 3600*24*$vall['start_day'];
                        }
                        $reult['valid_start_time']  = $timeL;
                        $end_time  = $time + 3600*24*$vall['duration_day'];
                        $reult['valid_end_time']    = strtotime(date("Y-m-d",$end_time)." 23:59:59");
                    }
                    Db::name('coupon')->insertGetId($reult);
                }
                //发送消息
                if($vall['money_type'] == 1){
                    $number = $vall['money']/100;
                    $content = "会员返优惠券-小马出行优惠券".$number."元";
                }
                $message = [
                    'uid'       => $value['uid'],
                    'status'    => 1,
                    'is_read'   => 0,
                    'content'   => $content,
                    'send_time' => time(),
                    'type'      => 1,
                    'order_type'=> $vall['order_type']
                ];
                Db::name('passenger_message')->insertGetId($message);
            }
        }
        echo '222';
        die;*/
        return $this->fetch();
    }
    public function sql(){
       //  $url_ip='http://ip.taobao.com/service/getIpInfo.php?ip=117.136.53.246';
       // $res =  self::curls1($url_ip);
       // echo "<pre>";
       // print_r($res);
       // echo "</pre>";
       // exit;
        set_time_limit(0);
        $list = Db::table('xm_user')->where("register_ip != 0 and register_province is null and referee_id != 0")->order('uid desc')->limit(5)->select();
        echo "<pre>";
        print_r($list);
        echo "</pre>";
        foreach ($list as $key => $value) {
            $str =  self::must_get_loacl($value['register_ip']);
            $res = json_decode($str,true);
            if($res['data']['region_id'] != 'xx'){
                $data['register_province'] = Db::name('region')->where('region_code',$res['data']['region_id'])->value('region_id');
            }

            if($res['data']['city_id'] != 'xx'){
                $data['register_city'] = Db::name('region')->where('region_code',$res['data']['city_id'])->value('region_id');
            }
            if($res['data']['country'] != 'xx'){
                $data['nation'] = $res['data']['country'];
            }
            $rr = Db::name('user')->where('uid',$value['uid'])->update($data);
            echo "<pre>";
            print_r($data);
            echo "</pre>";
        }

    }
    public static function must_get_loacl($ipmac){

        $url_ip='http://ip.taobao.com/service/getIpInfo.php?ip='.$ipmac;
        $str = self::curls1($url_ip);
        $json = json_decode($str,true);

        if(!$json['data']['country']){
            self::must_get_loacl($ipmac);
        }else{
            return $str;
        }
    }
    public function curls1($url){
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        // curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        return $data;
    }
    public function menulist(){

        return $this->fetch();

    }
    public function http(){
        $http = input('post.http');
        session('http',$http);
        if(session('http')){
            echo session('http');
        }else{
            echo 1;
        }
    }
    public function sec(){
        $str = $_POST['str'];
        $app_type = $_POST['app_type'];
        if($app_type == 3){
            echo json_encode(['code'=>JoDES::encode($str,"xmcx0551")]);
        }else{
            echo json_encode(['code'=>Security::encrypt($str)]);
        }
    }
    public function dec(){
        $mistr = $_POST['mistr'];
        $length = strlen($mistr);
        $mistr1 = substr($mistr, 2,$length-2);
        $mistr2 = substr($mistr1, 0,$length-4);
        $app_type = $_POST['app_type'];
        if($app_type == 3){
            echo "<pre>";
            print_r(json_decode(des_decode1($mistr2),true));
            echo "</pre>";
        }else{
            // echo $mistr;
            // echo '<br>';
            // echo $mistr2;
            // exit;
            echo "<pre>";
            print_r(json_decode(Security::decrypt($mistr2),true));
            echo "</pre>";
        }

        //echo Security::decrypt($mistr2);

    }
    public function apilist()
    {
        $type = input('get.type') ? input('get.type') : 1;
        $page = input('get.page');
        $limit= input('get.limit');

        if($page && $limit){
            $where['type'] = $type;
            if(input('get.title')){
                $where['title'] = ['like','%'.input('get.title').'%'];
            }
            if(input('get.api')){
                $where['url'] = ['like','%'.input('get.api').'%'];
            }
            $start = ($page -1)*$limit;
            $list =  Db::table('api')->where($where)->limit($start,$limit)->order('id desc')->select();
            $count =  Db::table('api')->where($where)->limit($start,$limit)->order('id desc')->count();
            echo json_encode(array('code'=>0,
                                    'msg'=>'',
                                    'count'=>$count,
                                    'data'=>$list
                                ));
            exit;
        }
        $this->assign('type',$type);
        return $this->fetch();
    }
    public function apilist_del(){
        $id = $_POST['id'];
        $res = Db::table('api')->where('id',$id)->delete();
        if($res){
            echo json_encode(['code'=>0]);
        }else{
            echo json_encode(['code'=>1]);
        }
    }
    public function apilist_add()
    {
        if(IS_POST){
            $data['title'] = $_POST['title'];
            $data['time'] = date('Y-m-d H:i:s',time());
            $data['name'] = json_encode($_POST['name']);
            if($_POST['name555']){
                $data['filename'] = json_encode($_POST['name555']);
            }
            $data['val'] = json_encode($_POST['val']);
            $data['bak'] = json_encode($_POST['bak']);
            $data['result'] = $_POST['result'];
            $data['url'] = $_POST['url'];
            $data['type'] = $_POST['type'];
            Db::table('api')->insert($data);
            $url = url('index/index/apilist',['type'=>$data['type']]);
            $this->redirect($url);
        }
        $type = input('get.type') ? input('get.type') : 1;
        $this->assign('type',$type);
        return $this->fetch();
    }
    public function apilist_edit()
    {

        if(IS_POST){
            $data['title'] = $_POST['title'];
            $data['time'] = date('Y-m-d H:i:s',time());
            $data['name'] = json_encode($_POST['name']);
            if($_POST['name555']){
                $data['filename'] = json_encode($_POST['name555']);
            }

            $data['val'] = json_encode($_POST['val']);
            $data['bak'] = json_encode($_POST['bak']);
            $data['result'] = $_POST['result'];
            $data['url'] = $_POST['url'];
            Db::table('api')->where('id',$_POST['id'])->update($data);
            $url = url('index/index/apilist',['type'=>$_POST['type']]);
            $this->redirect($url);

        }else{
            $id = input('get.id');
            $type = input('get.type');
            $data = Db::table('api')->where('id',$id)->find();
            $data['name'] = json_decode($data['name'],true);
            $data['val'] = json_decode($data['val'],true);
            $data['bak'] = json_decode($data['bak'],true);
            if($data['filename']){
                $data['filename'] = json_decode($data['filename'],true);
            }
            $this->assign('type',$type);
            $this->assign('data',$data);
            return $this->fetch();
        }

    }
    public function test(){
        $app_type = $_GET['app_type'];
        $type = $_GET['type'];
        $url = session('http').$_GET['url'];
        $str = $_GET['str'];


        if($app_type == 3){
            $data['encode'] = JoDES::encode($str,"xmcx0551");
            switch ($type) {
                case 1:
                $result = $this->httpsRequest($url,$data);
                //echo des_decode1($result);
                echo "<pre>";
                print_r(json_decode(des_decode1($result),true));
                echo "</pre>";
                    break;
                case 2:
                $result = $this->httpsRequest($url,$data);
                     /*echo "<pre>";
                     print_r(json_decode(des_decode1($result),true));
                     echo "</pre>";*/

                echo "<pre>";
                    print_r($result);
                echo "</pre>";
                break;
            }
        }else{
            $data['encode'] = Security::encrypt($str);
            switch ($type) {
                case 1:
                $result = $this->httpsRequest($url,$data);
                echo "<pre>";
                print_r(json_decode(Security::decrypt($result),true));
                echo "</pre>";
                    break;
                case 2:
                $result = $this->httpsRequest($url,$data);
                    echo "<pre>";
                    print_r(json_decode(Security::decrypt($result),true));
                    echo "</pre>";
                    echo "<pre>";
                    print_r(json_decode(des_decode1($result),true));
                    echo "</pre>";
                echo "<pre>";
                print_r($result);
                echo "</pre>";
                    exit;
                break;
            }
        }
    }
    public function httpsRequest($url, $data = null) {
        $curl = curl_init ();
        curl_setopt ( $curl, CURLOPT_URL, $url );
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE );
        if (! empty ( $data )) {
            curl_setopt ( $curl, CURLOPT_POST, 1 );
            curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data );
        }
        curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
        $output = curl_exec ( $curl );
        curl_close ( $curl );
        return $output;
    }

    public function api_log(){
        set_time_limit(0);
        $context = stream_context_create(array(
             'https' => array(
              'timeout' => 3000 //超时时间，单位为秒
             )
        ));
        $str =  file_get_contents('https://m.xiaomachuxing.cn/runtime/log/'.date('Ym',time()-86400).'/'.(date('d',time()-86400)).'.log',0, $context);

        $arr = explode('---------------------------------------------------------------', $str);
        $newarr = array();
        foreach ($arr as $key => $value) {
            $v = explode('[ log ]', $value);
            if(preg_match('/\/api\//', $v[0]) || preg_match('/\/inter\//', $v[0])){
                preg_match('/\[(.*?)\]/', $v[0],$mat);
                $newarr[$key]['time'] = strtotime(trim($mat[1]));
                $newarr[$key]['url'] = json_encode($v[0]);
                $newarr[$key]['content'] = json_encode($value);
                preg_match('/ \'encode\' => \'(.*)\'/', $value,$mags);
                $newarr[$key]['param'] = $mags[1];
                Db::table('api_log')->insert($newarr[$key]);
            }

        }
    }

    public function driver_agreement(){
        return view();
    }


}
